// stores/user.js
import { defineStore } from 'pinia'
import api from '@/api'
import router from '@/router'

export const useUserStore = defineStore('user', {
  state: () => ({
    library_token: localStorage.getItem('library_token'),  // 修正token读取来源
    roles: [],
    library_users: JSON.parse(localStorage.getItem('library_users') || '{}') // 添加初始化
  }),

  getters: {
    hasToken: (state) => !!state.token
  },

  actions: {
    // 登录方法
    async login(userInfo) {
      console.log('[用户存储] 开始登录流程，用户名:', userInfo.username.substring(0, 3) + '***');
      try {
        const res = await api.user.login(userInfo);
        console.log('[用户存储] 登录API响应:', { code: res.code, token: res.data?.token ? '***' + res.data.token.slice(-5) : '无' });
        
        this.token = res.data.token;
        localStorage.setItem('library_token', res.data.token);
        console.log('[用户存储] Token已存储');

        const data = { userId: res.data.id };
        console.log('[用户存储] 开始获取用户信息，用户ID:', data.userId);
        
        const infoRes = await api.user.getInfo(data);
        console.log('[用户存储] 用户信息响应:', {
          roles: infoRes.data?.roles,
          userId: infoRes.data?.userId
        });

        this.library_users = infoRes.data;
        this.roles = infoRes.data.roles;
        localStorage.setItem('library_users', JSON.stringify(infoRes.data));
        console.log('[用户存储] 用户信息存储完成');

        return Promise.resolve(res);
      } catch (error) {
        console.error('[用户存储] 登录流程异常:', {
          message: error.message,
          stack: error.stack
        });
        return Promise.reject(error);
      }
    },

    // 登出方法
    async logout() {
      this.$reset()
      localStorage.removeItem('token')
      router.push('/login')
    },

    $reset() { // 自定义重置方法
      this.token = ''
      this.name = ''
      this.avatar = ''
      this.roles = []
    }
  },

  // 开启持久化（需要安装插件 pinia-plugin-persistedstate）
  persist: {
    paths: ['token', 'library_users'],  // 修正持久化字段
    storage: localStorage
  }
})
